import react from 'react'
import './index.css'
export default class LinkFrom extends react.Component<LinkBacktop> {
  state: Readonly<LinkBacktop>;
  constructor(props: LinkBacktop) {
    super(props)
    console.log(props);
    // 参数可参考文档
    this.state = {
      scrollY: props.scrollY ? props.scrollY : 0,
      children: props.children ? props.children : '顶部',
      color: props.color ? props.color : '#fff',
      fontSize: props.fontSize ? props.fontSize : '16px',
      backgroundColor: props.backgroundColor ? props.backgroundColor : '#000',
      borderColor: props.borderColor ? props.borderColor : 'transparent',
    }

  }
  // 渲染
  render(): react.ReactNode {
    const { isShow, children, clientWidth, color, fontSize, backgroundColor, borderColor } = this.state
    return (
      <div className='top' onClick={this.blackTop} style={{
        right: isShow ? '30px' : '-' + (clientWidth as number + 30) + 'px',
        color,
        fontSize,
        backgroundColor,
        borderColor,
        opacity:isShow?'1':'0',
      }}>
        {children}
      </div>
    )
  }
  // 生命周期
  componentDidMount() {
    this.scroolTop()
    this.scroll();
  }
  // 返回顶部方法
  blackTop = () => {
    let timer = setInterval(() => {
      window.scroll(0, window.scrollY - 50);
      if (window.scrollY === 0) {
        clearInterval(timer)
      }
    }, 15);
  }
  // 监听滚轮
  scroll = () => {
    window.addEventListener('scroll', this.scroolTop.bind(this));
  }
  // 设置后显示按钮
  scroolTop() {
    let top = document.querySelector('.top')
    const clientWidth = top?.clientWidth
    const { scrollY: scroll } = this.state
    let scrollY = scroll as number
    if (window.scrollY >= scrollY) {
      this.setState({
        isShow: true
      })
    } else {
      this.setState({
        isShow: false,
        clientWidth
      })
    }

  }
}